<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增拜访日志')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-visit_log-add">
        <div class="form-group" id="unitDiv3" style="display: none">
            <label class="col-sm-3 control-label is-required">三级单元：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unitSelect3"
                        name="unitId3"
                        onchange="setNextUnitSelect(this.value, 3)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group" id="unitDiv4" style="display: none">
            <label class="col-sm-3 control-label is-required">四级单元：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unitSelect4"
                        name="unitId4"
                        onchange="setNextUnitSelect(this.value, 4)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group" id="unitDiv5" style="display: none">
            <label class="col-sm-3 control-label is-required">包区名称：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unitSelect5"
                        name="unitId5"
                        onchange="setNextUnitSelect(this.value, 5)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">网格名称：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unitSelect6"
                        name="unitId6"
                        onchange="setSelect7(this.value)"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">村庄/街道/小区名称：</label>
            <div class="col-sm-8">
                <select class="form-control"
                        id="unitSelect7"
                        name="unitId7"
                        required>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">用户类型：</label>
            <div class="col-sm-8">
                <select class="form-control" name="communicationOperator"
                        onchange="setExpiredTimeSelectRequired(this.value)" required
                        th:with="type=${@dict.getType('communication_operators')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">用户姓名：</label>
            <div class="col-sm-8">
                <input class="form-control" maxlength="20" name="userName" required type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">当前号码：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input class="form-control" id="currentPhoneNumber" maxlength="11" name="currentPhoneNumber"
                           placeholder="请输入手机号码" required type="text">
                    <span class="input-group-addon"><i class="fa fa-mobile"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">套餐价值：</label>
            <div class="col-sm-8">
                <input class="form-control" name="mealValue" required type="number">
            </div>
        </div>
        <div class="form-group" id="expiredTimeDiv">
            <label class="col-sm-3 control-label" id="expiredTimeLabel">到期时间：</label>
            <div class="col-sm-8">
                <div class="input-group date">
                    <input class="form-control time-input"
                           id="expiredTimeInput"
                           name="expiredTime"
                           placeholder="yyyy-MM-dd"
                           type="text">
                    <span class="input-group-addon">
                        <i class="fa fa-calendar"></i>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">转化号码：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input class="form-control" id="translatedPhoneNumber" maxlength="11"
                           name="translatedPhoneNumber"
                           placeholder="请输入手机号码" type="text">
                    <span class="input-group-addon"><i class="fa fa-mobile"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">现场照片：</label>
            <div class="col-sm-8">
                <input id="scenePhotoId" name="scenePhoto" required type="hidden">
                <div class="file-loading">
                    <input accept="image/*" class="form-control file-upload" id="scenePhoto" name="file"
                           onclick="judgeStatus()"
                           type="file">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">备注：</label>
            <div class="col-sm-8">
                <textarea class="form-control" name="remake"></textarea>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<script th:inline="javascript">
    let prefix = ctx + "workbench/visit_log";
    let maxImageCount = 5;
    $("#form-visit_log-add").validate({
        focusCleanup: true,
        onkeyup: false,
        rules: {
            currentPhoneNumber: {
                isPhone: true,
                remote: {
                    url: prefix + "/checkPhoneNumberUnique",
                    type: "post",
                    dataType: "json",
                    data: {
                        type: '',
                        phoneNumber: function () {
                            return $.common.trim($("#currentPhoneNumber").val());
                        }
                    },
                    dataFilter: function (data, type) {
                        return $.validate.unique(data);
                    }
                }
            },
            translatedPhoneNumber: {
                isPhone: true,
                remote: {
                    url: prefix + "/checkPhoneNumberUnique",
                    type: "post",
                    dataType: "json",
                    data: {
                        type: '1',
                        phoneNumber: function () {
                            return $.common.trim($("#translatedPhoneNumber").val());
                        }
                    },
                    dataFilter: function (data, type) {
                        return $.validate.unique(data);
                    }
                }
            }
        },
        messages: {
            "currentPhoneNumber": {
                remote: "手机号码已经录入"
            },
            "translatedPhoneNumber": {
                remote: "手机号码已经转化"
            },
        }
    });

    /**
     * 设置过期时间是否必填，异网用户必填，本网用户和潜在用户可填可不填
     */
    function setExpiredTimeSelectRequired(value) {
        let expiredTimeInput = document.getElementById('expiredTimeInput')
        if (value === '6') {
            $('#expiredTimeLabel').addClass('is-required')
            expiredTimeInput.setAttribute('required', 'required')
        } else {
            $('#expiredTimeLabel').removeClass('is-required')
            expiredTimeInput.removeAttribute('required')
        }
        $("#expiredTimeDiv").selectpicker('refresh')
    }

    function submitHandler() {
        if ($.validate.form()) {
            if ($('#unitSelect7').val() === null) {
                $.modal.alertError("请先在所辖村庄中添加自然庄/街道/小区");
                return
            }
            if ($('#currentPhoneNumber').val() === $('#translatedPhoneNumber').val()) {
                $.modal.alertError('转化号码不能与当前号码相同');
                return
            }
            $.operate.save(prefix + "/add", $('#form-visit_log-add').serialize());
        }
    }

    function getImageCount() {
        return $(".file-preview-thumbnails").find('.file-preview-frame').length / 2;
    }

    function judgeStatus() {
        if (getImageCount() >= maxImageCount) {
            $('#scenePhoto').attr('disabled', 'disabled');
            $.modal.msg("图片允许上传的最大数值为" + maxImageCount + "，请删除需要被替换的图片后再进行上传操作!");
        }
    }

    let scenePhotoInputer = $("#scenePhotoId");
    $(".file-upload").fileinput({
        uploadUrl: ctx + 'common/upload',
        initialPreviewAsData: true,
        maxFileCount: maxImageCount,
        overwriteInitial: false,
        allowedFileTypes: ['image'],
        allowedPreviewTypes: ['image'],
    }).on('fileuploaded', function (event, data) {
        let images = scenePhotoInputer.val();
        if (images === '') {
            images = data.response.url;
        } else {
            images = images + ',' + data.response.url;
        }
        scenePhotoInputer.val(images)
    }).on("filebatchselected", function () {
        // 文件选择完直接调用上传方法。
        $(this).fileinput("upload");
    }).on('filesuccessremove', function (event, id, index) {
        let images = scenePhotoInputer.val();
        let imageArray = images.split(',');
        imageArray.splice(Number(index), 1);
        scenePhotoInputer.val(imageArray.toString());
        if (getImageCount() <= maxImageCount) {
            $('#scenePhoto').removeAttr('disabled');
        }
    });

    $(function () {
        $.ajax({
            method: 'post',
            url: '/workbench/leaf_unit/selectHighestLevelDeptsByLoginName',
            success: function (dept) {
                let level = dept.level;
                if (level !== 2) {
                    setPreviousUnitSelect(dept.parentId, level);
                }
                setCurrentSelect(dept, level);
                setNextUnitSelect(dept.deptId, level);
            }
        })
    })

    /**
     * 设置上级单元选择器
     * @param parentId 当前选择的项
     * @param level 单元等级
     */
    function setPreviousUnitSelect(parentId, level) {
        $.ajax({
            method: 'post',
            url: '/system/dept/selectByDeptId',
            data: {
                deptId: parentId
            },
            success: function (previousUnit) {
                let selectId
                switch (level) {
                    case 6:
                        selectId = "#unitSelect5"
                        setPreviousUnitSelect(previousUnit.parentId, 5)
                        break
                    case 5:
                        selectId = "#unitSelect4"
                        setPreviousUnitSelect(previousUnit.parentId, 4)
                        break
                    case 4:
                        selectId = "#unitSelect3"
                        break
                    case 3:
                        break
                    default:
                        console.log("单元等级错误p：" + level)
                }
                let option = "<option value='" + previousUnit.deptId + "'>" + previousUnit.deptName + "</option>"
                $(selectId).html(option).selectpicker('refresh');
            }
        })
    }

    /**
     * 设置当前选择器的值
     */
    function setCurrentSelect(dept, level) {
        let selectId
        switch (level) {
            case 6:
                selectId = "#unitSelect6"
                break
            case 5:
                selectId = "#unitSelect5"
                break
            case 4:
                selectId = "#unitSelect4"
                break
            case 3:
                selectId = "#unitSelect3"
                break
            case 2:
                return;
            default:
                console.log("单元等级错误")
        }
        let options = "<option value='" + dept.deptId + "'>" + dept.deptName + "</option>";
        $(selectId).html(options).selectpicker('refresh');
    }

    /**
     * 设置下级单元选择器
     * @param deptId 本单元id
     * @param level 本单元等级
     */
    function setNextUnitSelect(deptId, level) {
        $.ajax({
            method: 'post',
            url: '/system/dept/selectChildrenDeptById',
            data: {
                deptId: deptId,
                phone: 3
            },
            success: function (list) {
                let options = "";
                for (let i = 0; i < list.length; i++) {
                    let option = list[i];
                    options += "<option value='" + option.deptId + "'>" + option.deptName + "</option>";
                }
                let selectId
                let liId;
                switch (level) {
                    case 6:
                        break;
                    case 5:
                        selectId = "#unitSelect6";
                        liId = "#unitDiv5";
                        setSelect7(list[0].deptId);
                        break;
                    case 4:
                        selectId = "#unitSelect5";
                        liId = "#unitDiv4";
                        setNextUnitSelect(list[0].deptId, 5);
                        break;
                    case 3:
                        selectId = "#unitSelect4";
                        liId = "#unitDiv3";
                        setNextUnitSelect(list[0].deptId, 4);
                        break;
                    case 2:
                        setNextUnitSelect(list[0].deptId, level + 1);
                        selectId = "#unitSelect3";
                        break;
                    default:
                        console.log("单元等级错误n：" + level);
                }
                $(selectId).html(options).selectpicker('refresh');
                if (liId !== '') {
                    $(liId).show();
                }
            }
        })
    }

    /**
     * 点击六级单元，设置七级单元
     * @param unitId7
     */
    function setSelect7(unitId7) {
        $.ajax({
            method: 'post',
            url: '/workbench/leaf_unit/selectChildrenUnitByParentId',
            data: {
                parentId: unitId7
            },
            success: function (list) {
                let options = "";
                for (let i = 0; i < list.length; i++) {
                    let option = list[i];
                    options += "<option value='" + option.unitId + "'>" + option.unitName + "</option>";
                }
                $("#unitSelect7").html(options).selectpicker('refresh');
            }
        })
    }
</script>
</body>
</html>
